package com.campus.dao.impl;

import com.campus.dao.ActivityDao;
import com.campus.model.Activity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Repository
@Slf4j
public class ActivityDaoImpl implements ActivityDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public int createActivity(Activity activity) {
        String sql = "INSERT INTO t_manager_activity " +
                "(name, category, title, creator, abstract, detailed_desc, status, created_time, archived_time, pic_urls, start_time, end_time) " +
                "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        try {
            return jdbcTemplate.update(sql,
                    activity.getName(),
                    activity.getCategory(),
                    activity.getTitle(),
                    activity.getCreator(),
                    activity.getAbstract(),
                    activity.getDetailedDesc(),
                    activity.getStatus() != null ? activity.getStatus() : 0,
                    new Timestamp(System.currentTimeMillis()),
                    activity.getArchivedTime() != null ? new Timestamp(activity.getArchivedTime().getTime()) : null,
                    activity.getPicUrls(),
                    activity.getStartTime() != null ? new Timestamp(activity.getStartTime().getTime()) : null,
                    activity.getEndTime() != null ? new Timestamp(activity.getEndTime().getTime()) : null
            );
        } catch (Exception e) {
            log.error("Error creating activity: " + e.getMessage(), e);
        }
        return -1;
    }

    @Override
    public int updateActivity(Activity activity) {
        String sql = "UPDATE t_manager_activity SET " +
                "name = ?, category = ?, title = ?, creator = ?, abstract = ?, detailed_desc = ?, " +
                "status = ?, archived_time = ?, pic_urls = ?, start_time = ?, end_time = ? " +
                "WHERE id = ?";
        try {
            return jdbcTemplate.update(sql,
                    activity.getName(),
                    activity.getCategory(),
                    activity.getTitle(),
                    activity.getCreator(),
                    activity.getAbstract(),
                    activity.getDetailedDesc(),
                    activity.getStatus(),
                    activity.getArchivedTime() != null ? new Timestamp(activity.getArchivedTime().getTime()) : null,
                    activity.getPicUrls(),
                    activity.getStartTime() != null ? new Timestamp(activity.getStartTime().getTime()) : null,
                    activity.getEndTime() != null ? new Timestamp(activity.getEndTime().getTime()) : null,
                    activity.getId()
            );
        } catch (Exception e) {
            log.error("Error updating activity: " + e.getMessage(), e);
        }
        return 0;
    }

    @Override
    public int publishActivity(int activityId) {
        String sql = "UPDATE t_manager_activity SET status = 1 WHERE id = ?";
        try {
            return jdbcTemplate.update(sql, activityId);
        } catch (Exception e) {
            log.error("Error publishing activity: " + e.getMessage(), e);
        }
        return 0;
    }

    @Override
    public List<Activity> queryActivities(Integer status, String name, String orderBy) {
        String sql = "SELECT * FROM t_manager_activity WHERE 1=1";
        List<Object> params = new ArrayList<>();
        if (status != null) {
            sql += " AND status = ?";
            params.add(status);
        }
        if (name != null) {
            sql += " AND name LIKE ?";
            params.add("%" + name + "%");
        }
        sql += " ORDER BY " + (orderBy != null ? orderBy : "created_time") + " DESC";

        return jdbcTemplate.query(sql, params.toArray(), (rs, rowNum) -> {
            Activity activity = new Activity();
            activity.setId(rs.getInt("id"));
            activity.setName(rs.getString("name"));
            activity.setCategory(rs.getString("category"));
            activity.setTitle(rs.getString("title"));
            activity.setCreator(rs.getString("creator"));
            activity.setAbstract(rs.getString("abstract"));
            activity.setDetailedDesc(rs.getString("detailed_desc"));
            activity.setStatus(rs.getInt("status"));
            activity.setCreatedTime(rs.getTimestamp("created_time"));
            activity.setArchivedTime(rs.getTimestamp("archived_time"));
            activity.setPicUrls(rs.getString("pic_urls"));
            activity.setStartTime(rs.getTimestamp("start_time"));
            activity.setEndTime(rs.getTimestamp("end_time"));
            return activity;
        });
    }

    @Override
    public Optional<Activity> findById(int activityId) {
        String sql = "SELECT * FROM t_manager_activity WHERE id = ?";
        try {
            return Optional.ofNullable(jdbcTemplate.queryForObject(sql, new Object[]{activityId}, (rs, rowNum) -> {
                Activity activity = new Activity();
                activity.setId(rs.getInt("id"));
                activity.setName(rs.getString("name"));
                activity.setCategory(rs.getString("category"));
                activity.setTitle(rs.getString("title"));
                activity.setCreator(rs.getString("creator"));
                activity.setAbstract(rs.getString("abstract"));
                activity.setDetailedDesc(rs.getString("detailed_desc"));
                activity.setStatus(rs.getInt("status"));
                activity.setCreatedTime(rs.getTimestamp("created_time"));
                activity.setArchivedTime(rs.getTimestamp("archived_time"));
                activity.setPicUrls(rs.getString("pic_urls"));
                activity.setStartTime(rs.getTimestamp("start_time"));
                activity.setEndTime(rs.getTimestamp("end_time"));
                return activity;
            }));
        } catch (Exception e) {
            log.error("Error finding activity by ID: " + e.getMessage(), e);
        }
        return Optional.empty();
    }

    @Override
    public List<Activity> findAllActivities() {
        String sql = "SELECT * FROM t_manager_activity";
        return jdbcTemplate.query(sql, new RowMapper<Activity>() {
            @Override
            public Activity mapRow(ResultSet rs, int rowNum) throws SQLException {
                Activity activity = new Activity();
                activity.setId(rs.getInt("id"));
                activity.setName(rs.getString("name"));
                activity.setCategory(rs.getString("category"));
                activity.setTitle(rs.getString("title"));
                activity.setCreator(rs.getString("creator"));
                activity.setAbstract(rs.getString("abstract"));
                activity.setDetailedDesc(rs.getString("detailed_desc"));
                activity.setStatus(rs.getInt("status"));
                activity.setCreatedTime(rs.getTimestamp("created_time"));
                activity.setArchivedTime(rs.getTimestamp("archived_time"));
                activity.setPicUrls(rs.getString("pic_urls"));
                activity.setStartTime(rs.getTimestamp("start_time"));
                activity.setEndTime(rs.getTimestamp("end_time"));
                return activity;
            }
        });
    }

    @Override
    public boolean deleteActivity(int id) {
        String sql = "DELETE FROM t_manager_activity WHERE id = ?";
        return jdbcTemplate.update(sql, id) > 0;
    }

}

